﻿package little.bunny.server;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import android.util.Log;

public class GetSource {
	
	
	public String getSource_bk(String url,String encode,int overtime){
		InputStream in = null;   
		ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
		String content = "";
		long nowTime = new Date().getTime();
		try {
			   in = new java.net.URL(url).openStream();   
			   
				//new Thread().sleep(10000);
				byte[] b = new byte[1024];     
				int len = 0;
				while ((len = in.read(b, 0, 1024)) != -1)
				{	
					if(new Date().getTime()-nowTime>overtime*1000){
						System.out.println("响应超时");
						baos.close();
						return "";
					}
						
					baos.write(b, 0, len);
					baos.flush();
				}
				
				byte[] bytes = baos.toByteArray();
				content = new String(bytes,encode);
		} 
		catch (MalformedURLException e) {  
			  System.out.println("URL异常");   
		} catch (IOException e) {  
			   System.out.println("网络连接异常");
		}finally{
			   try {
				   if(in!=null)
					   in.close();
				   if(baos!=null)
					   baos.close();
			   } catch (IOException e) {
				System.out.println("关闭异常");
			   }
		}
		   //new String(bytes);
		return content;
	}
	
	public static String getSource(String uri, String encode,int overtime) {
		StringBuilder sb = new StringBuilder();
		try
		{
			
			String value="";
			HttpPost request = new HttpPost(uri);
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("key", value));
	
			//request.setEntity(new UrlEncodedFormEntity(params, encode));
			 
			HttpParams httpParams = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(httpParams, overtime*1000);
			HttpConnectionParams.setSoTimeout(httpParams, 5000);
			HttpClient client = new DefaultHttpClient(httpParams);
			//client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 4500);
			HttpResponse response = client.execute(request);
			if (response.getStatusLine().getStatusCode() == 200) {  
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				BufferedReader reader = new BufferedReader(new InputStreamReader(
						entity.getContent(), encode), 8192);
				String line = null;
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				reader.close();
			}
			}
		}   
		catch(Exception e1)
		{
			Log.v("net",e1.getMessage());
		}
		/////////////Log.v("SB",sb.toString());
		if(sb.length()>0)
			return sb.toString();
		else
			return null;
		
	}
	/**
	 * 获取网页源码
	 * @param url	网址
	 * @param encode	编码方式（gbk/gb2312/utf-8......）
	 * @return	返回网页源码
	 */
	public String getSource2(String url,String encode){
		String source = "";
		try {
			InputStream is = new URL(url).openStream();
			byte[] b = new byte[1024];
	        if (is == null) {
	            return "";
	        }
	        int bytesRead = 0;
	        while (true) {
	        	bytesRead = is.read(b, 0, 1024);
	        	if (bytesRead == -1) {
	        		 is.close();
	                 return source;
	        	}
	        	source = source + new String(b, 0, bytesRead, encode);
	        }
		} catch (MalformedURLException e) {
			System.out.println("请检查URL是否正确...");
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println("请检查网络连接是否正确...");
			e.printStackTrace();
		}
		return source;
	}
	
	/**
	 * 获取匹配正则表达式的字符串
	 * @param content	字符串内容
	 * @param regex		正则表达式
	 * @return	返回匹配正则表达式的字符串列表
	 */
	public static List<String> getList(String content,String regex) {
		List<String> list = new ArrayList<String>();
		Pattern pattern = Pattern.compile(regex,Pattern.MULTILINE);
		Matcher matcher = pattern.matcher(content);
		while (matcher.find()) {
			if (!list.contains(matcher.group()))
				list.add(matcher.group());
		}
		return list;
	}
	
	/**
	 * 将content根据给定的mod和split进行切割
	 * @param content 	内容源码
	 * @param mod		内容模板
	 * @param split		要切割的内容的标记
	 * @return	返回切割后的数组
	 */
	public String[] getModSplit(String content,String mod,String split){
		String[] s = mod.split(split);
		int j = s.length;
		for(int i=0;i<j;i++){
			if(i==0||i==j-1){
				content = content.replaceFirst(s[i], "");
			}else{
				content = content.replaceFirst(s[i], "&lst;");
			}
		}
		String[] str = content.split("&lst;");
		return str;
	}
	
	/**
	 * 将String根据给定的开始标记和结束标记进行切割
	 * @param source	源码
	 * @param start		开始标记
	 * @param end		结束标记
	 * @return		返回新的String
	 */
	public String getContent(String source,String start,String end){
		int a = source.indexOf(start);
		int b = source.indexOf(end);
		String str = "";
		if(a<b){
			str = source.substring(a,b);
		}else{
			System.out.println("数组越界异常");
		}
		return str;
	}
	
	/**
	 * 将String根据给定的开始标记、结束标记和位置进行切割
	 * @param source		源码
	 * @param start			开始标记
	 * @param startnum		在第几个开始标记开始
	 * @param end			结束标记
	 * @param endnum		在第几个结束标记结束
	 * @return			返回新的String
	 */
	public String getContent(String source,String start,int startnum,String end,int endnum){
		int c = start.length();
		int a = 0;
		for(int i=0;i<startnum;i++){
			a = source.indexOf(start, a);
			a = a + c;
		}
		c = end.length();
		int b = 0;
		for(int i=0;i<endnum;i++){
			b = source.indexOf(end, b+end.length());
			b = b+c;
		}
		String str = "";
		if(a<b){
			str = source.substring(a,b);
		}else{
			System.out.println("数组越界异常");
		}
		return str;
	}

}
